<template>
  <div class="brand-sales-page">
    <!-- 顶部信息卡片 -->
    <div class="info-card">
      <div class="info-content">
        <!-- 左侧图片 -->
        <div class="info-image">
          <img src="/banner2.jpg" alt="品牌销量分析" />
        </div>
        <!-- 右侧文字 -->
        <div class="info-text">
          <h2>
            📊 各品牌销量与总销售额分析
          </h2>
          <p class="desc">
            本图表展示各品牌商品的销量和总销售金额，支持直观比较热门品牌表现及市场占比。
          </p>
        </div>
      </div>
    </div>

    <!-- 图表卡片 -->
    <div class="chart-card">
      <div class="chart-container" ref="chartRef"></div>
      <p class="note">提示：柱形图表示销量（件），折线图表示总销售额（元）</p>
    </div>

    <!-- 下载按钮 -->
    <div class="download-wrapper">
      <button class="download-btn" @click="downloadChart">下载图表文件</button>
    </div>

    <!-- 页面底部 Footer -->
    <FooterInfo />
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'
import FooterInfo from '../components/FooterInfo.vue'

// 图表引用
const chartRef = ref(null)
let chartInstance = null
const chartData = ref([])

// 品牌映射：英文 => 中文
const brandMap = {
  samsung: '三星',
  apple: '苹果',
  ava: '阿瓦',
  tefal: '特福',
  lg: 'LG',
  xiaomi: '小米',
  philips: '飞利浦',
  polaris: '北极星',
  huawei: '华为',
  bosch: '博世',
  asus: '华硕',
  sony: '索尼',
  beko: '倍科',
  lenovo: '联想',
  neo: '尼奥',
  oppo: 'OPPO',
  hp: '惠普',
  vitek: '维他克',
  braun: '博朗'
}

// 初始化图表
onMounted(async () => {
  await nextTick()
  const el = chartRef.value
  if (!el) return
  chartInstance = echarts.init(el)
  chartInstance.setOption({
    tooltip: { trigger: 'axis' },
    legend: { data: ['销量', '总销售额'] },
    xAxis: { type: 'category', data: [] },
    yAxis: [
      { type: 'value', name: '销量 (件)' },
      { type: 'value', name: '总销售额 (元)', position: 'right' }
    ],
    series: []
  })

  await fetchData()
})

// 请求数据
async function fetchData() {
  try {
    const res = await axios.get('http://localhost:8080/queryBrandOfSales')
    if (res.data.code === 200) {
      chartData.value = res.data.data.map(item => ({
        brand: item.brand ? brandMap[item.brand] || item.brand : '其他',
        salesCount: item.salesCount || 0,
        totalSales: Number(item.totalSales) || 0
      }))
      updateChart()
    } else {
      alert('获取品牌数据失败')
    }
  } catch (err) {
    console.error(err)
    alert('请求接口失败，请检查网络或接口地址')
  }
}

// 更新图表
function updateChart() {
  if (!chartInstance || !chartData.value.length) return
  chartInstance.setOption({
    xAxis: {
      data: chartData.value.map(d => d.brand),
      axisLabel: {
        rotate: 45,       // X轴标签旋转45度
        interval: 0,      // 保证每个标签都显示
        fontSize: 12,
        color: '#333'
      }
    },
    series: [
      {
        name: '销量',
        type: 'bar',
        data: chartData.value.map(d => d.salesCount),
        itemStyle: { color: '#4a90e2' },
        yAxisIndex: 0,
        barCategoryGap: '20%' // 调整柱子间距
      },
      {
        name: '总销售额',
        type: 'line',
        data: chartData.value.map(d => d.totalSales),
        itemStyle: { color: '#ff6f61' },
        yAxisIndex: 1
      }
    ]
  })
}

// 下载图表
function downloadChart() {
  if (!chartInstance) return
  const url = chartInstance.getDataURL({
    type: 'png',
    pixelRatio: 2,
    backgroundColor: '#fff'
  })
  const link = document.createElement('a')
  link.href = url
  link.download = 'brand-sales-chart.png'
  link.click()
}
</script>

<style scoped>
.brand-sales-page {
  max-width: 1000px;
  margin: 40px auto;
  font-family: 'Segoe UI', sans-serif;
}

/* 顶部信息卡片 */
.info-card {
  background: #fff;
  padding: 25px 30px;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
  margin-bottom: 25px;
}

.info-content {
  display: flex;
  align-items: flex-start;
  gap: 20px;
}

.info-image img {
  width: 240px;
  height: auto;
  border-radius: 8px;
  object-fit: cover;
  margin-top: 70px;
}

.info-text {
  flex: 1;
}

.info-text h2 {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 12px;
  color: #333;
}

.info-text .desc {
  font-size: 15px;
  color: #555;
  line-height: 1.8;
  text-align: justify;
}

/* 图表卡片 */
.chart-card {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
  padding: 20px;
  margin-bottom: 20px;
}

.chart-container {
  width: 100%;
  height: 400px;
}

.note {
  text-align: center;
  font-size: 13px;
  color: #888;
  margin-top: 10px;
}

/* 下载按钮 */
.download-wrapper {
  text-align: center;
  margin-bottom: 30px;
}

.download-btn {
  background: #ff7f50;
  color: #fff;
  padding: 10px 22px;
  border: none;
  border-radius: 6px;
  font-size: 15px;
  cursor: pointer;
  transition: background 0.3s;
}

.download-btn:hover {
  background: #ff6333;
}
</style>
